package com.han.controller;

import cn.hutool.core.util.ObjectUtil;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.han.common.annotation.IgnoreToken;
import com.han.common.constant.HttpStatus;
import com.han.core.controller.BaseController;
import com.han.core.domain.RestResult;
import com.han.service.AuthService;
import com.han.service.ProductService;
import com.han.service.ShopService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController extends BaseController {
    private final AuthService authService;
    private final ShopService shopService;
    private final ProductService productService;


    /**
     * 通过传递店铺的code来获取独属于店铺的access_token
     *
     * @param code 店铺专属code
     * @return access_token
     */
    @GetMapping("/token/get")
    @IgnoreToken(required = true)
    public RestResult getToken(@RequestParam("code") String code) {
        //1.缓存access_token和refresh_token
        //2.判断店铺是否存在，不存在则新增
        //3.返回给前端一个access_token
        AccessToken accessToken = AccessTokenBuilder.build(code);
        if (ObjectUtil.isNull(accessToken)) {
            log.warn("注入code获取AccessToken异常，对象值为空");
            return RestResult.error(HttpStatus.ERROR, "注入code获取AccessToken异常");
        }
        // 10000 属于 sdk中正常返回，先不创建枚举;
        if (!Objects.equals(accessToken.getCode(), "10000")) {
            log.warn("注入code时返回结果异常,异常状态：{}，异常描述:{}", accessToken.getCode(), accessToken.getMsg());
            return RestResult.error(HttpStatus.ERROR, "注入code获取AccessToken异常");
        }
        authService.setTokenCache(accessToken.getData());
        //todo 还未添加购买天数功能，默认为10
        Boolean isNewShop = shopService.saveNewShop(accessToken.getData(), 10);
        // 需要执行一个异步拉取商品的数据，
        if (isNewShop) {
            productService.pullAllProductAsync(accessToken.getData());
        }
        return RestResult.success("", accessToken.getAccessToken());
    }


}
